import { defineStore } from "pinia";
import { ref } from 'vue'
import { getDicts } from '@/api/system/dict/data'

const storeDict = defineStore('dictData', {
    persist: true,
    state: () => {
        return {
            dictData: {}
        }
    },
    actions: {
        // 获取字典数据
        getDict(dictName) {
            // 传过来的字典名称不能为空
            if(!dictName && dictName === null || !dictName.length) return null
            const dictStore = this.dictData

            // 必须为一个数组，且 长度大于1
            if(dictName instanceof Array && dictName.length >= 1) {
                for(let i = 0; i < dictName.length; i++) {
                     // 如果有对应的字典数据，则不请求数据:如果没有则请求
                    if(!Object.keys(dictStore)?.includes(dictName[i])) {
                        this.requestDict(dictName[i])
                    }
                }
            }else {
                // 当字典名称为字符串的时候
                if(!Object.keys(dictStore)?.includes(dictName)) {
                    this.requestDict(dictName)
                }
            }
        },
        // 获取异步数据
        async requestDict(dictName) {
            const { data: dictData } = await getDicts(dictName)
            this.dictData[dictName] = ref(dictData)
        }
    }
})

export default storeDict
